package search;

import fj.F;
import global.Global;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import server.db.DatabaseFunctor;
import server.db.StmtHelper;
import server.objects.User;

import ajaxmethods.AjaxMethod;
import ajaxmethods.SessionMethod;

public class PerformSaveSearch extends SessionMethod {

	private List<String> requiredFields = Arrays.asList("searchname");
	private Map<String,String> searchFields = new HashMap();
	private Map<String,String> saveSearchFields = new HashMap();
	private JSONArray errors = new JSONArray();

	@Override
	public void perform(HttpServletRequest request, HttpServletResponse response) {
		super.perform(request, response);
		response.setContentType("text/json");
		String fields = request.getParameter("searchInputs");
		for(String field : fields.split(","))
		{
			String[] fvPair = field.split(":");
			if(fvPair.length>1)
			{
				searchFields.put(fvPair[0],fvPair[1]);
			}
		}
		fields = request.getParameter("genericInputs");
		for(String field : fields.split(","))
		{
			String[] fvPair = field.split(":");
			if(fvPair.length>1)
			{
				saveSearchFields.put(fvPair[0],fvPair[1]);
			}
		}
		validate();
		if(errors.length()<1)
		{
			Global global = new Global(request);
			User user = global.getUser();
			try {
				StmtHelper.db("insert into savedsearch (iduser,createdate,searchname) values (")
					.addVariable(user.id).addSql(",")
					.addSql("NOW()").addSql(",")
					.addVariable(saveSearchFields.get("searchname")).addSql(")").executeUpdate().provideTo(new F<Integer,DatabaseFunctor<List<Integer>>>() {

						@Override
						public DatabaseFunctor<List<Integer>> f(Integer inserted) {
								List<DatabaseFunctor<Integer>> inserts = new ArrayList<DatabaseFunctor<Integer>>();
								if(inserted!=null)
								{
									for(String key : searchFields.keySet())
									{
										if(searchFields.get(key)!=null && !"".equals(searchFields.get(key)))
											inserts.add(StmtHelper.db("insert into searchcriteria (idsavedsearch,fieldid,fieldvalue) values (")
													.addVariable(String.valueOf(inserted)).addSql(",")
													.addVariable(key).addSql(",")
													.addVariable(searchFields.get(key)).addSql(")")
													.executeUpdate());
									}
									return DatabaseFunctor.sequence(inserts);
								}
								return null;
							}
						
					}).unsafeUpdate();
					
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			
		}
	}
	
	
	private void validate() {
		//check requiredness
		for(String fieldName : requiredFields)
		{
			if(saveSearchFields.get(fieldName)==null ||"".equals(saveSearchFields.get(fieldName)))
				addError("required",fieldName);
		}
	}
	
	private void addError(String errortype, String fieldName) {
		JSONObject error;
		try {
			error = new JSONObject().put("error", errortype).put("fieldname",fieldName);
			errors.put(error);
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
	}

}
